const Router = require('koa-router');
const {db, Op,QueryTypes } = require("../../models/db");
const tool = require("../../tools/tool");
const router = new Router(); 

const request = require('request');
// 库存余额表写期初数
router.post('/goods/barCodeToInfo', async ctx => {
    let code = ctx.request.body.barCode;
    if (!code) {
        return ctx.err('请输入条码')
    }
    const options = {
        url: `https://jisutxmcx.market.alicloudapi.com/barcode2/query?barcode=${code}`, // 请求的URL
        method: 'GET', // 请求方法
        headers: {
            'Authorization': 'APPCODE e9e94a4886cf43c081e9948e9e57f982', // 设置请求头
        },
    };
    let goods = await db.models['goods'].findOne({
        where: {
            tenantId: ctx.user.tenantId,
            [Op.or]:{
                barCode: code,
                barCode1: code,
            }
        }
    })
    if (goods) {
        return ctx.suc('', {
            exist: true, // 已存在
            goods
        })
    }
    else {
        const response = await new Promise((resolve, reject) => {
            request(options, (error, response, body) => {
                if (error) {
                    reject(error);
                } else {
                    resolve(body);
                }
            });
        });
        let res = JSON.parse(response)
        let spec = null
/**
        if(res.result.type) {
            if(res.result.type.indexOf('12') !== -1) {
                spec = 12
            }
            if(res.result.type.indexOf('24') !== -1) {
                spec = 24
            }
            if(res.result.type.indexOf('6') !== -1) {
                spec = 6
            }
            if(res.result.type.indexOf('16') !== -1) {
                spec = 16
            }
            if(res.result.type.indexOf('8') !== -1) {
                spec = 8
            }
        }
*/
        goods = {
            name: res.result.name,
            spec,
            barCode: code,
        }
        return ctx.suc('', {
            exist: false,
            goods
        })
    }
})
// 查询商品库存
router.post('/app/searchGoodStock', async ctx => {
    let formData = ctx.request.body.formData;
    let currentPage = ctx.request.body.currentPage?ctx.request.body.currentPage:1;
    let pageSize = 20;
    let offset = (currentPage-1) *pageSize;
    let tenantId = ctx.user.tenantId;
    let searchTxt = tool.xe.trim(formData.searchTxt)
    let listSql = `select * from goods where tenantId=${tenantId}`
    if(searchTxt) {
        listSql += ` and(name like '%${searchTxt}%' or code ='${searchTxt}') `;
    }
    listSql += ` order by id desc offset ${offset} rows fetch next ${pageSize} rows only;`
    let list = await db.query(listSql, {type: QueryTypes.SELECT})
    return ctx.suc('', list)

})
router.post('/app/getGoods', async ctx => {
    let formData = ctx.request.body.formData;
    let currentPage = ctx.request.body.currentPage?ctx.request.body.currentPage:1;
    let pageSize = 20;
    let offset = (currentPage-1) *pageSize;
    let tenantId = ctx.user.tenantId;
    let searchTxt = tool.xe.trim(formData.searchTxt)
    let listSql = `select * from goods where tenantId=${tenantId} `
    let totalSql = `select count(*) total from goods where tenantId=${tenantId} `
    if(searchTxt) {
        listSql += ` and(name like '%${searchTxt}%' or code ='${searchTxt}') `;
        totalSql += ` and(name like '%${searchTxt}%' or code ='${searchTxt}') `;
    }
    listSql += ` order by id desc offset ${offset} rows fetch next ${pageSize} rows only;`
    let total = await db.query(totalSql, {type: QueryTypes.SELECT, plain: true})
    let list = await db.query(listSql, {type: QueryTypes.SELECT})
    return ctx.suc('', {total: total.total, list })

})
router.post('/app/getUnit', async ctx => {
    let list = await db.query(`select name as value, name as label from unit order by sort `, {type: QueryTypes.SELECT});
    return ctx.suc('', list)

})
router.post('/app/getGoodCat', async ctx => {
    let tenantId = ctx.user.tenantId
    let list = await db.query(`select id as value, name as label from goods_cat where tenantId=${tenantId}`, {type: QueryTypes.SELECT});
    return ctx.suc('', list)

})

router.post('/app/saveGood', async ctx => {
    let formData = ctx.request.body.formData
    let tenantId = ctx.user.tenantId
    let goodModel = null;
    if(formData.name.indexOf('[') !== -1) return ctx.err('不能包含字符[')
    if(formData.name.indexOf(']') !== -1) return ctx.err('不能包含字符]')

    if(formData.id) {
        let has = await db.models['goods'].findOne({
            where: {
                tenantId,
                name: formData.name,
                id: {
                    [Op.ne]: formData.id
                }
            }
        })
        if(has) {
            return  ctx.err('已存在相同名称')
        }
        goodModel = await db.models['goods'].findOne({
            where: {
                id: formData.id,
                tenantId
            }
        })
        let hasDetail = await db.models['invoiceInfo'].findOne({
            where: {
                tenantId,
                invId: formData.id
            }
        })
        if(hasDetail) {
            if (tool.xe.toNumber(goodModel.spec) !== tool.xe.toNumber(formData.spec)) {
                return  ctx.err('已使用商品，不能修改规格')
            }
        }
        goodModel.barCode = formData.barCode
        goodModel.barCode1 = formData.barCode1
        goodModel.pinYin = tool.py(formData.name)
        goodModel.categoryId = formData.categoryId
        goodModel.name = formData.name
        goodModel.spec = formData.spec
        goodModel.unit1 = formData.unit1
        goodModel.unit2 = formData.unit2
        goodModel.price1 = formData.price1
        goodModel.price2 = formData.price2
        await goodModel.save()
    }
    else {
        let has = await db.models['goods'].count({
            where: {
                tenantId,
                name: formData.name
            }
        })
        if(has > 0) {
            return  ctx.err('已存在相同名称')
        }

        goodModel = db.models['goods'].build();
        goodModel.tenantId = tenantId
        goodModel.barCode = formData.barCode
        goodModel.barCode1 = formData.barCode1
        goodModel.pinYin = tool.py(formData.name)
        goodModel.categoryId = formData.categoryId
        goodModel.name = formData.name
        goodModel.spec = formData.spec
        goodModel.unit1 = formData.unit1
        goodModel.unit2 = formData.unit2
        goodModel.price1 = formData.price1
        goodModel.price2 = formData.price2
        await goodModel.save()
    }
    return ctx.suc('保存成功')
})


module.exports = router;
